import React from 'react';
import { Button } from 'antd';
import NewWebSocket from '../../utils/websocketC';
import { FirstHeaderC } from '../../comps';

const config = {
  url: 'http://168.61.9.181:7001/msgserver-server/invstres-websocket?iv-user=010211',
  // url:`msgserver-server/invstres-websocket?iv-user=${ivUser}`,
  headers: {
    Authorization: '',
  },
  id: 'sub-1',
  subscribeUrl: '/user/topic/stock/realtime/price',
};
class Websockets extends React.Component {
  constructor() {
    super();
    this.state = {
      result: '', // 通过订阅获取的后端推送的消息
      connect: false, // 标记当前连接状态
    };
  }

  componentWillUnmount() {
    // 结束进行websocket
    NewWebSocket({
      ...config,
      connectCall: (res) => {
        this.setState({
          connect: res,
        });
      },
    }).disconnect();
  }

  // 结束websocket
  disconnect = () => {
    // 结束进行websocket
    NewWebSocket({
      ...config,
      connectCall: (res) => {
        this.setState({
          connect: res,
        });
      },
    }).disconnect();
  };

  // 连接websocket
  initWebSocket = () => {
    const ivUser = '010211';
    // 开始进行websocket
    NewWebSocket({
      ...config,

      // 收到服务端消息
      callback: (res) => {
        if (res) {
          this.setState({
            result: res?.body || '',
          });
        }
      },
      // 接收连接状态变更
      connectCall: (res) => {
        this.setState({
          connect: res,
        });
      },
    }).connect();
  };

  // 向服务端发送消息
  send = () => {
    const sendUrl = '/topic/stocks';
    const sendParams = JSON.stringify({
      name: '00013',
    });
    NewWebSocket({ ...config }).send(sendUrl, { name: '00013222' }, sendParams);
  };

  // 取消订阅
  unsubscribeFn = () => {
    NewWebSocket({
      ...config,
    }).unsubscribe();
  };

  // 继续订阅
  subscribeFn = () => {
    NewWebSocket({
      ...config,
    }).subscribe();
  };

  render() {
    const { result, connect } = this.state;
    return (
      <>
        <div style={{ margin: '20px' }}>
          <FirstHeaderC title='基于http请求进行websocket通讯' />
          <Button onClick={this.initWebSocket} disabled={connect}>
            连接websocket
          </Button>
          <Button onClick={this.unsubscribeFn} disabled={!connect}>
            取消订阅
          </Button>
          <Button onClick={this.subscribeFn} disabled={!connect}>
            继续订阅
          </Button>
          <Button onClick={this.disconnect} disabled={!connect} style={{ marginLeft: '20px' }}>
            结束websocket
          </Button>
          <Button onClick={this.send} disabled={!connect} style={{ marginLeft: '20px' }}>
            向服务端发送消息
          </Button>
          <h2 style={{ margin: '20px' }}>下面是获取websocket的值：</h2>
          <h1>{result}</h1>
        </div>
      </>
    );
  }
}
export default Websockets;
